package controller;

import view.Stage;
import model.ModelRW;
import model.world.World;

public class Controller{
	private ModelRW world;
	private Clock clock;
	private Action combinedAction;
	private boolean CRAFT_TABLE_STATE;


	private Controller(){
		World tempWorldLink = new World();
		clock = new Clock();
		clock.addGameClockListener(tempWorldLink);

		world = tempWorldLink;
		world.newGame();
		Stage stage = new Stage(world, this);
		clock.addDrawingClockListener(stage);
		stage.setVisible(true);
		combinedAction = Action.NULL;
		CRAFT_TABLE_STATE = false;
	}

	public static void main(String[] args){
		new Controller();
	}

	public void leftClickTile(long x, long y) {
		if(combinedAction == Action.NULL){
			world.setSelectedTile(x, y);
		}else if(combinedAction == Action.MOVE && world.selectedIsPlayer()){
			world.setSelectedEntityTarget(x, y);
			combinedAction = Action.NULL;
		}
	}

	public void rightClickTile(long x, long y) {
		if(world.selectedIsPlayer()){
			world.setSelectedEntityTarget(x, y);
		}
	}

	public void clickMove() {
		combinedAction = Action.MOVE;
	}

	public void clickWork() {
		world.entityWorkTile();
	}

	public void clickHalt() {
		world.entityHaltWorking();
	}

	public void clickEntity(String name) {
		if(world.entitySelected()){
			world.setSelectedItemID(Integer.parseInt(name));
		}else{
			world.setSelectedEntity(name);
		}
	}

	public void leftClickCrafting(long x, long y) {
		if(x == -1 && y == -1){
			world.removeCraftingOutput();
		}else{
			world.addSelectedItem(x, y);
		}
	}

	public void rightClickCrafting(long x, long y) {
		world.removeSelectedItem(x, y);
	}

	public void clickPlaceItem() {
		world.placeSelectedItem();
	}

	public boolean isCraftingOpen() {
		return CRAFT_TABLE_STATE;
	}

	public void clickCraftTable() {
		if(isCraftingOpen()) {
			CRAFT_TABLE_STATE = false;
		}else {
			CRAFT_TABLE_STATE = true;
		}
	}
}
